package com.clgc.eduservice.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.clgc.eduservice.config.security.JwtTokenUtils;
import com.clgc.eduservice.entity.EduTeacher;
import com.clgc.eduservice.mapper.EduTeacherMapper;
import com.clgc.eduservice.service.EduTeacherService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.clgc.utils.MD5Utils;
import com.clgc.utils.R;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 老师表 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2021-04-27
 */
@Service
public class EduTeacherServiceImpl extends ServiceImpl<EduTeacherMapper, EduTeacher> implements EduTeacherService {
    //老师注册
    @Override
    public Boolean teacherRegister(EduTeacher eduTeacher) {
        Md5Hash md5Hash = new Md5Hash(eduTeacher.getPwd(), null, 1024);
        eduTeacher.setPwd(md5Hash.toHex());
        int i = baseMapper.insert(eduTeacher);
        return i > 0;
    }

    @Qualifier("myUserDetailsService")
    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtils jwtTokenUtils;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

//    @Autowired
//    private PasswordEncoder passwordEncoder;
    //老师注册
//    @Override
//    public Boolean teacherRegister(EduTeacher eduTeacher) {
//        Md5Hash md5Hash = new Md5Hash(eduTeacher.getPwd(),null,1024);
//        eduTeacher.setPwd(md5Hash.toHex());
//        int i = baseMapper.insert(eduTeacher);
//        return i > 0;
//    }
//

    /**
     * 老师信息更新
     *
     * @param eduTeacher
     * @return
     */
    @Override
    public R login(String username, String pwd, HttpServletRequest request) {
        EduTeacher userDetails = (EduTeacher) userDetailsService.loadUserByUsername(username);
        //检验用户是否存在，密码是否正确，是否逻辑删除为1
        if (null == userDetails || !MD5Utils.MD5Encode(pwd).equals(userDetails.getPwd()) || userDetails.getIsDelete() == 1) {
            return R.error().message("用户名或密码错误");
        }

        //设置全局用户对象
        UsernamePasswordAuthenticationToken authenticationToken
                = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        String token = jwtTokenUtils.generateToken(userDetails);
        String userNameFromToken = jwtTokenUtils.getUserNameFromToken(token);
        System.out.println(userNameFromToken);
        System.out.println("----------生成token------------");
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        System.out.println("------------------");
        System.out.println(SecurityContextHolder.getContext().getAuthentication());
        System.out.println("------------------");
        return R.ok().message("登陆成功").data(tokenMap);
    }

    /**
     * 获取老师信息
     *
     * @param username
     * @return
     */
    @Override
    public EduTeacher getTeacherByUsername(String username) {
        QueryWrapper<EduTeacher> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        EduTeacher teacher = baseMapper.selectOne(wrapper);
        if (teacher == null) {
            return null;
        }
        return teacher;
    }

    @Override
    public boolean updateEduTeacher(EduTeacher eduTeacher) {
        UpdateWrapper<EduTeacher> wrapper = new UpdateWrapper<>();
        String pwd = eduTeacher.getPwd();
        Md5Hash md5Hash = new Md5Hash(pwd, null, 1024);
        eduTeacher.setPwd(md5Hash.toHex());
        int i = baseMapper.updateById(eduTeacher);
        return i > 0;
    }
}
